import 'dart:async';
import 'package:fishing/providers/auth_provider.dart';
import 'package:fishing/providers/user_provider.dart';
import 'package:fishing/services/auth_service.dart';
import 'package:fishing/widgets/message_overlay.dart';
import 'package:flutter/services.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:provider/provider.dart';
import 'package:go_router/go_router.dart';

class LoginPage extends StatefulWidget {
  const LoginPage({super.key});

  @override
  State<LoginPage> createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  // 使用独立的状态管理，避免外部状态影响
  final phoneController = TextEditingController();
  final codeController = TextEditingController();
  final _formKey = GlobalKey<FormState>();
  
  // 本地状态管理 - 不依赖Provider的状态变化
  bool _isSendingCode = false;
  bool _isLoading = false;
  bool _isLoginLoading = false;
  int _countdown = 0;
  Timer? _timer;
  String _savedPhoneNumber = ''; // 保存手机号的本地副本

  @override
  void initState() {
    super.initState();
    // 监听手机号输入变化，实时保存
    phoneController.addListener(() {
      _savedPhoneNumber = phoneController.text;
    });
  }

  @override
  void dispose() {
    phoneController.dispose();
    codeController.dispose();
    _timer?.cancel();
    super.dispose();
  }

  // 验证手机号
  bool _validatePhone() {
    if (_savedPhoneNumber.isEmpty) {
      MessageOverlay.error(context, '请输入手机号');
      return false;
    }
    if (!RegExp(r'^1[3-9]\d{9}$').hasMatch(_savedPhoneNumber)) {
      MessageOverlay.error(context, '请输入有效的手机号');
      return false;
    }
    return true;
  }

  // 开始倒计时
  void _startCountdown() {
    setState(() {
      _countdown = 60;
      _isSendingCode = true;
    });

    _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      if (_countdown <= 1) {
        timer.cancel();
        setState(() { 
          _isSendingCode = false;
          _countdown = 0;
        });
      } else {
        setState(() {
          _countdown--;
        });
      }
    });
  }

  // 发送验证码 - 完全独立实现
  Future<void> _sendCode() async {
    // 确保手机号不会被清空
    final phone = _savedPhoneNumber.trim();
    if (!_validatePhone()) return;

    setState(() {
      _isLoading = true;
    });

    try {
      // 直接调用 AuthService，避免 Provider 的状态影响
      final authService = AuthService();
      await authService.getSmsCode(phone);
      
      if (!mounted) return;

      _startCountdown();
      MessageOverlay.success(context, '验证码已发送到 $phone');
    } catch (e) {
      if (mounted) {
        MessageOverlay.error(context, '验证码发送失败，请稍后重试');
      }
    } finally {
      if (mounted) {
        setState(() {
          _isLoading = false;
        });
      }
    }
  }

  // 登录 - 完全独立实现，避免Provider影响
  Future<void> _onLogin() async {
    if (!_formKey.currentState!.validate()) return;

    // 在开始登录前保存所有输入内容，防止被清空
    final phone = _savedPhoneNumber.trim();
    final code = codeController.text.trim();
    
    // 验证输入
    if (phone.isEmpty) {
      MessageOverlay.error(context, '请输入手机号');
      return;
    }
    if (code.isEmpty) {
      MessageOverlay.error(context, '请输入验证码');
      return;
    }

    setState(() {
      _isLoginLoading = true;
    });

    try {
      // 直接调用 AuthService，避免 Provider 的影响
      final authService = AuthService();
      final success = await authService.login(phone, code);
      
      if (!mounted) return;

      if (success) {
        // 登录成功，更新用户信息
        final userProvider = Provider.of<UserProvider>(context, listen: false);
        final authProvider = Provider.of<AuthProvider>(context, listen: false);
        
        await userProvider.fetchUserInfo();
        authProvider.setLoggedIn(true);
        
        if (mounted) {
          MessageOverlay.success(context, '登录成功');
          
          Future.delayed(const Duration(milliseconds: 800), () {
            if (mounted) {
              context.go('/home');
            }
          });
        }
      } else {
        // 登录失败时确保输入框内容不丢失
        if (mounted) {
          WidgetsBinding.instance.addPostFrameCallback((_) {
            if (phoneController.text != phone) {
              phoneController.text = phone;
              _savedPhoneNumber = phone;
            }
            if (codeController.text != code) {
              codeController.text = code;
            }
          });
          
          MessageOverlay.error(context, '登录失败，请检查手机号和验证码');
        }
      }
    } catch (e) {
      if (mounted) {
        // 网络错误时也确保输入框内容不丢失
        WidgetsBinding.instance.addPostFrameCallback((_) {
          if (phoneController.text != phone) {
            phoneController.text = phone;
            _savedPhoneNumber = phone;
          }
          if (codeController.text != code) {
            codeController.text = code;
          }
        });
        
        MessageOverlay.error(context, '网络错误，请稍后重试');
      }
    } finally {
      if (mounted) {
        setState(() {
          _isLoginLoading = false;
        });
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: const Color(0xFF4286DE),
        resizeToAvoidBottomInset: false, // 防止键盘弹起时背景图移动
        body: Stack(
          children: [
            // 固定背景图片，不受键盘影响
            Positioned.fill(
              child: Container(
                width: double.infinity,
                height: double.infinity,
                decoration: const BoxDecoration(
                  image: DecorationImage(
                    image: AssetImage('assets/images/login_bg.png'),
                    fit: BoxFit.cover,
                  ),
                ),
              ),
            ),
            // 可滚动的内容区域
            Positioned.fill(
              child: SafeArea(
                child: SingleChildScrollView(
                  padding: EdgeInsets.only(
                    bottom: MediaQuery.of(context).viewInsets.bottom, // 为键盘留出空间
                  ),
                  child: ConstrainedBox(
                    constraints: BoxConstraints(
                      minHeight: MediaQuery.of(context).size.height - 
                                MediaQuery.of(context).padding.top - 
                                MediaQuery.of(context).padding.bottom -
                                MediaQuery.of(context).viewInsets.bottom, // 减去键盘高度
                    ),
                    child: Column(
                  children: [
                    // Logo区域
                    Container(
                      margin: const EdgeInsets.only(top: 40, bottom: 40),
                      child: Column(
                        children: [
                          // Logo图片 - 使用SVG
                          Container(
                            width: 90,
                            height: 90,
                            padding: const EdgeInsets.all(18),
                            decoration: BoxDecoration(
                              color: Colors.white.withOpacity(0.95),
                              shape: BoxShape.circle,
                              boxShadow: [
                                BoxShadow(
                                  color: Colors.black.withOpacity(0.2),
                                  blurRadius: 20,
                                  offset: const Offset(0, 10),
                                ),
                              ],
                            ),
                            child: SvgPicture.asset(
                              'assets/images/logo.svg',
                              width: 54,
                              height: 54,
                              fit: BoxFit.contain,
                              colorFilter: const ColorFilter.mode(
                                Color(0xFF4286DE),
                                BlendMode.srcIn,
                              ),
                              placeholderBuilder: (context) => const Icon(
                                Icons.pool,
                                size: 45,
                                color: Color(0xFF4286DE),
                              ),
                            ),
                          ),
                          const SizedBox(height: 24),
                          // 应用名称
                          const Text(
                            '鱼乐无限',
                            style: TextStyle(
                              fontSize: 36,
                              fontWeight: FontWeight.bold,
                              color: Color(0xFF4286DE),
                              letterSpacing: 3,
                              shadows: [
                                Shadow(
                                  color: Color(0xFFFFFFFF),
                                  offset: Offset(0, 2),
                                  blurRadius: 4,
                                ),
                                Shadow(
                                  color: Color(0x40000000),
                                  offset: Offset(0, 1),
                                  blurRadius: 2,
                                ),
                              ],
                            ),
                          ),
                          const SizedBox(height: 12),
                          const Text(
                            '让你每次钓鱼都充满欢乐',
                            style: TextStyle(
                              fontSize: 18,
                              color: Color(0xFF2E5BBA),
                              fontWeight: FontWeight.w400,
                              letterSpacing: 1.5,
                              shadows: [
                                Shadow(
                                  color: Color(0xFFFFFFFF),
                                  offset: Offset(0, 1),
                                  blurRadius: 3,
                                ),
                                Shadow(
                                  color: Color(0x30000000),
                                  offset: Offset(0, 1),
                                  blurRadius: 2,
                                ),
                              ],
                            ),
                          ),
                        ],
                      ),
                    ),
                    
                    // 登录表单区域
                    Container(
                      margin: const EdgeInsets.symmetric(
                          horizontal: 20, vertical: 10),
                      padding: const EdgeInsets.symmetric(
                          horizontal: 20, vertical: 10),
                      decoration: BoxDecoration(
                        color: Colors.white,
                        borderRadius: BorderRadius.circular(12),
                        boxShadow: const [
                          BoxShadow(
                            color: Colors.black12,
                            blurRadius: 10,
                            offset: Offset(0, 4),
                          ),
                        ],
                      ),
                      child: Form(
                        key: _formKey,
                        child: Column(
                          children: [
                            // 手机号输入框
                            TextFormField(
                              controller: phoneController,
                              keyboardType: TextInputType.phone,
                              style: const TextStyle(
                                color: Color(0xFF2C3E50),
                                fontSize: 16,
                                fontWeight: FontWeight.w500,
                              ),
                              decoration: const InputDecoration(
                                labelText: '手机号',
                                hintText: '请输入手机号',
                                hintStyle: TextStyle(color: Color(0xFFBDC3C7)),
                                labelStyle: TextStyle(color: Color(0xFF5D6D7E)),
                                border: UnderlineInputBorder(
                                  borderSide:
                                      BorderSide(color: Color(0xFF4286DE)),
                                ),
                                focusedBorder: UnderlineInputBorder(
                                  borderSide: BorderSide(
                                      color: Color(0xFF4286DE), width: 2),
                                ),
                              ),
                              validator: (value) {
                                if (value == null || value.isEmpty) {
                                  return '请输入手机号';
                                }
                                if (!RegExp(r'^1[3-9]\d{9}$').hasMatch(value)) {
                                  return '请输入有效的手机号';
                                }
                                return null;
                              },
                            ),
                            const SizedBox(height: 16),
                            // 验证码输入框和获取验证码按钮
                            Row(
                              children: [
                                Expanded(
                                  child: TextFormField(
                                    controller: codeController,
                                    maxLength: 4,
                                    maxLengthEnforcement:
                                        MaxLengthEnforcement.enforced,
                                    buildCounter: (context,
                                        {required currentLength,
                                        required isFocused,
                                        required maxLength}) {
                                      return null; // 隐藏计数器文本
                                    },
                                    style: const TextStyle(
                                      color: Color(0xFF2C3E50),
                                      fontSize: 16,
                                      fontWeight: FontWeight.w500,
                                    ),
                                    keyboardType: TextInputType.number,
                                    decoration: const InputDecoration(
                                      labelText: '验证码',
                                      hintText: '请输入验证码',
                                      hintStyle: TextStyle(color: Color(0xFFBDC3C7)),
                                      labelStyle: TextStyle(color: Color(0xFF5D6D7E)),
                                      border: UnderlineInputBorder(
                                        borderSide: BorderSide(
                                            color: Color(0xFF4286DE)),
                                      ),
                                      focusedBorder: UnderlineInputBorder(
                                        borderSide: BorderSide(
                                            color: Color(0xFF4286DE), width: 2),
                                      ),
                                    ),
                                    validator: (value) {
                                      if (value == null || value.isEmpty) {
                                        return '请输入验证码';
                                      }
                                      return null;
                                    },
                                  ),
                                ),
                                const SizedBox(width: 8),
                                // 获取验证码按钮
                                SizedBox(
                                  height: 45,
                                  width: 120,
                                  child: ElevatedButton(
                                    onPressed: (_isSendingCode || _isLoading) ? null : _sendCode,
                                    style: ElevatedButton.styleFrom(
                                        backgroundColor: Colors.white,
                                        foregroundColor: const Color(0xFF4286DE),
                                        disabledForegroundColor: const Color(0xFF666666),
                                        shape: RoundedRectangleBorder(
                                          borderRadius: BorderRadius.circular(2),
                                        ),
                                        elevation: 0,
                                        side: BorderSide(
                                          color: (_isSendingCode || _isLoading) 
                                              ? const Color(0xFFCCCCCC) 
                                              : const Color(0xFF4286DE),
                                          width: 1,
                                        ),
                                        disabledBackgroundColor: const Color(0xFFF8F8F8)),
                                    child: _isLoading
                                        ? const SizedBox(
                                            width: 16,
                                            height: 16,
                                            child: CircularProgressIndicator(
                                              strokeWidth: 2,
                                              valueColor: AlwaysStoppedAnimation<Color>(
                                                  Color(0xFF4286DE)),
                                            ),
                                          )
                                        : _isSendingCode
                                            ? Text(
                                                '等待 $_countdown 秒',
                                                style: const TextStyle(
                                                  color: Color(0xFF7F8C8D),
                                                  fontSize: 14,
                                                  fontWeight: FontWeight.w500,
                                                ),
                                              )
                                            : const Text(
                                                '获取验证码',
                                                style: TextStyle(
                                                  color: Color(0xFF4286DE),
                                                  fontSize: 14,
                                                  fontWeight: FontWeight.w600,
                                                ),
                                              ),
                                  ),
                                )
                              ],
                            ),
                            const SizedBox(height: 24),
                            // 登录按钮
                            SizedBox(
                              width: double.infinity,
                              height: 48,
                              child: ElevatedButton(
                                onPressed: _isLoginLoading ? null : _onLogin,
                                style: ElevatedButton.styleFrom(
                                    backgroundColor: const Color(0xFF4286DE),
                                    foregroundColor: const Color(0xFFFFFFFF),
                                    disabledForegroundColor: const Color(0xFFFFFFFF),
                                    side: const BorderSide(
                                        width: 0, color: Color(0xFF4286DE)),
                                    shape: RoundedRectangleBorder(
                                      borderRadius: BorderRadius.circular(2),
                                    ),
                                    disabledBackgroundColor: const Color(0xFFB3D1F0),
                                    elevation: 0),
                                child: const Text(
                                  '登录',
                                  style: TextStyle(
                                    color: Color(0xFFFFFEFE),
                                    fontSize: 16,
                                    fontWeight: FontWeight.w600,
                                    letterSpacing: 1,
                                  ),
                                ),
                              ),
                            ),
                          ],
                        ),
                      ),
                    ),
                    
                    // 底部间距
                    const SizedBox(height: 40),
                  ],
                    ),
                  ),
                ),
              ),
            ),
            // 全局登录loading遮罩
            if (_isLoginLoading)
              Container(
                width: double.infinity,
                height: double.infinity,
                color: Colors.black.withValues(alpha: 0.3),
                child: const Center(
                  child: Card(
                    elevation: 8,
                    child: Padding(
                      padding: EdgeInsets.all(24),
                      child: Column(
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          SizedBox(
                            width: 40,
                            height: 40,
                            child: CircularProgressIndicator(
                              strokeWidth: 3,
                              valueColor: AlwaysStoppedAnimation<Color>(
                                Color(0xFF4286DE),
                              ),
                            ),
                          ),
                          SizedBox(height: 16),
                          Text(
                            '登录中，请稍候...',
                            style: TextStyle(
                              fontSize: 16,
                              color: Color(0xFF333333),
                              fontWeight: FontWeight.w500,
                            ),
                          ),
                        ],
                      ),
                    ),
                  ),
                ),
              ),
          ],
        ));
  }
}